<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="生产批次" prop="productionBatch">
          <el-input
              v-model="queryParams.productionBatch"
              placeholder="生产批次"
              style="width: 250px"
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="产品型号" prop="spec">
          <el-input
              v-model="queryParams.spec"
              placeholder="产品型号"
              style="width: 250px"
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="生产时间" prop="startTime">
          <el-date-picker
              v-model="queryParams.startTime"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['system:sysDianciProductionRetrospect:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus/>
          </template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['system:sysDianciProductionRetrospect:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon>
            <Delete/>
          </template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column
            key="createTime"
            label="创建时间"
            prop="createTime"
            min-width="200"
            align="center"
        />
        <el-table-column
            key="productionBatch"
            label="生产批次"
            prop="productionBatch"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="spec"
            label="产品型号"
            prop="spec"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="num"
            label="计划数量"
            prop="num"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="realityNum"
            label="实际产量"
            prop="realityNum"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="percentOfPass"
            label="合格率"
            prop="percentOfPass"
            min-width="150"
            align="center"
        />
        <el-table-column label="生产状态" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.productionState" code="production_state"/>
          </template>
        </el-table-column>
        <el-table-column
            key="startTime"
            label="开始时间"
            prop="startTime"
            min-width="200"
            align="center"
        />
        <el-table-column
            key="endTime"
            label="结束时间"
            prop="endTime"
            min-width="200"
            align="center"
        />

        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:sysDianciProductionRetrospect:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['system:sysDianciProductionRetrospect:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 生产追溯表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="600px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">

        <el-form-item label="生产批次" prop="productionBatch">
          <el-input
              v-model="formData.productionBatch"
              placeholder="生产批次"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <el-form-item label="产品型号" prop="spec">
          <el-input
              v-model="formData.spec"
              placeholder="产品型号"
              clearable
              show-word-limit
              maxlength="64"
          />
        </el-form-item>

        <span class="flex flex-wrap gap-4">
          <el-form-item label="计划数量" prop="num">
          <el-input
              v-model="formData.num"
              placeholder="计划数量"
              clearable
              show-word-limit
              maxlength="10"
              style="width: 195px"
          />
        </el-form-item>

        <el-form-item label="实际产量" prop="realityNum">
          <el-input
              v-model="formData.realityNum"
              placeholder="实际产量"
              clearable
              show-word-limit
              maxlength="10"
              style="width: 195px"
          />
        </el-form-item>
        </span>

        <span class="flex flex-wrap gap-4">
        <el-form-item label="合格率" prop="percentOfPass">
          <el-input
              v-model="formData.percentOfPass"
              placeholder="合格率"
              clearable
              show-word-limit
              maxlength="10"
              style="width: 195px"
          />
        </el-form-item>

        <el-form-item label="生产状态" prop="productionState">
          <dict v-model="formData.productionState" code="production_state" style="width: 195px"/>
        </el-form-item>
        </span>
        <span class="flex flex-wrap gap-4">
          <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 195px"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 195px"
          />
        </el-form-item>
        </span>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              placeholder="备注"
              type="textarea"
              clearable
              show-word-limit
              maxlength="250"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SysDianciProductionRetrospect",
  inheritAttrs: false,
});

import Page1 from './page1.vue'

import SysDianciProductionRetrospectAPI, {
  SysDianciProductionRetrospectForm,
  SysDianciProductionRetrospectPageQuery,
  SysDianciProductionRetrospectPageVO
} from "@/api/system/sys-dianci-production-retrospect";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<SysDianciProductionRetrospectPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 生产追溯表格数据
const pageData = ref<SysDianciProductionRetrospectPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 生产追溯表单数据
const formData = reactive<SysDianciProductionRetrospectForm>({});

// 生产追溯表单校验规则
const rules = reactive({
  productionBatch: [{required: true, message: "请输入生产批次", trigger: "blur"}],
  spec: [{required: true, message: "请输入产品型号", trigger: "blur"}],
  num: [{required: true, message: "请输入计划数量", trigger: "blur"}],
  productionState: [{required: true, message: "请输入生产状态", trigger: "blur"}],
});

/** 查询生产追溯 */
function handleQuery() {
  loading.value = true;
  SysDianciProductionRetrospectAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置生产追溯查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开生产追溯弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改生产追溯";
    SysDianciProductionRetrospectAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增生产追溯";
  }
}

/** 提交生产追溯表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SysDianciProductionRetrospectAPI.update(id, formData)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        SysDianciProductionRetrospectAPI.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭生产追溯弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除生产追溯 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SysDianciProductionRetrospectAPI.deleteByIds(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
